//
//  MDHTabBarController.m
//  JSTech
//
//  Created by 高得华 on 2019/4/27.
//  Copyright © 2020 华&梅. All rights reserved.
//

#import "MDHTabBarController.h"
#if __has_include(<YYCategories/YYCategories.h>)
#import <YYCategories/YYCategories.h>
#else
#import "YYCategories.h"
#endif
#import "MDHPT.h"

///  自定义系统的TabBar，解决TabBar顶部的细线高度问题
@interface MDHTabBar ()
/// divider
@property (nonatomic, readwrite, weak) UIView *divider;
@end

@implementation MDHTabBar

- (instancetype)initWithFrame:(CGRect)frame
{
    self = [super initWithFrame:frame];
    if (self) {
        /// 去掉tabBar的分割线,以及背景图片 只有在实现setBackgroundImage：方法的情况下，setShadowImage：才会生效
        [self setShadowImage:[UIImage new]];
        [self setBackgroundImage:[UIImage imageWithColor:kColor_MDHHex(@"#FCFCFC")]];//kColor_MDHHex(@"180043")
        
        /// 添加细线,
        UIView *divider = [[UIView alloc] init];
        divider.backgroundColor = kColor_MDHHex(@"#F3F3F3");
        [self addSubview:divider];
        self.divider = divider;
        //divider.hidden = true;
    }
    return self;
}


#pragma mark - 布局
- (void)layoutSubviews
{
    [super layoutSubviews];
    
    [self bringSubviewToFront:self.divider];
    self.divider.mh_height = MHGlobalBottomLineHeight;
    self.divider.mh_y = -self.divider.mh_height;
    self.divider.mh_width = [[UIScreen mainScreen] bounds].size.width;
    /*self.divider.gradientAColor = [kColor_MDHEEEEEE() colorWithAlphaComponent:0.001];
    self.divider.gradientBColor = [kColor_MDHEEEEEE() colorWithAlphaComponent:0.54];
    self.divider.gradientStyle = GradientStyleTopToBottom;*/
}

///OC中重写TraitColletion方法
//重写traitCollection方法,使UITabbar保持图为垂直排列,防止在ipad11出现水平排列
- (UITraitCollection *)traitCollection {
    if (UIDevice.currentDevice.userInterfaceIdiom == UIUserInterfaceIdiomPad) {
        return [UITraitCollection traitCollectionWithVerticalSizeClass:UIUserInterfaceSizeClassCompact];
    }
    return [super traitCollection];
}


@end


@interface MDHTabBarController ()

/// The `tabBarController` instance
@property (nonatomic, readwrite, strong) CYLTabBarController * tabBarController;

@end

@implementation MDHTabBarController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    self.tabBarController = [[CYLTabBarController alloc] init];
    /// 添加子控制器
    [self.view addSubview:self.tabBarController.view];
    [self addChildViewController:self.tabBarController];
    [self.tabBarController didMoveToParentViewController:self];
    
    // kvc替换系统的tabBar
    MDHTabBar *tabbar = [[MDHTabBar alloc] init];
    //kvc实质是修改了系统的_tabBar
    [self.tabBarController setValue:tabbar forKeyPath:@"tabBar"];
    
    [self customizeTabBarAppearance:self.tabBarController];
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

#pragma mark - Ovveride
- (BOOL)shouldAutorotate {
    return self.tabBarController.selectedViewController.shouldAutorotate;
}

- (UIInterfaceOrientationMask)supportedInterfaceOrientations {
    return self.tabBarController.selectedViewController.supportedInterfaceOrientations;
}

- (UIStatusBarStyle)preferredStatusBarStyle {
    return self.tabBarController.selectedViewController.preferredStatusBarStyle;
}

- (BOOL)prefersStatusBarHidden{
    return self.tabBarController.selectedViewController.prefersStatusBarHidden;
}


/**
 *  更多TabBar自定义设置：比如：tabBarItem 的选中和不选中文字和背景图片属性、tabbar 背景图片属性等等
 */
- (void)customizeTabBarAppearance:(CYLTabBarController *)tabBarController {
    // Customize UITabBar height
    // 自定义 TabBar 高度
    //tabBarController.tabBarHeight = [MMWPTFileConfiguration share].kTabbarSafeArea;
    
    // set the text color for unselected state
    // 普通状态下的文字属性
    NSMutableDictionary *normalAttrs = [NSMutableDictionary dictionary];
    normalAttrs[NSForegroundColorAttributeName] = kColor_MDHHex(@"#363636");
    
    // set the text color for selected state
    // 选中状态下的文字属性
    NSMutableDictionary *selectedAttrs = [NSMutableDictionary dictionary];
    selectedAttrs[NSForegroundColorAttributeName] = kColor_MDHDarkMode(kColor_MDHTheme(), kColor_MDHHex(@"#FFFFFF"));
    
    // set the text Attributes
    // 设置文字属性
    UITabBarItem *tabBar = [UITabBarItem appearance];
    [tabBar setTitleTextAttributes:normalAttrs forState:UIControlStateNormal];
    [tabBar setTitleTextAttributes:selectedAttrs forState:UIControlStateSelected];
    
    // Set the dark color to selected tab (the dimmed background)
    // TabBarItem选中后的背景颜色
    //[self customizeTabBarSelectionIndicatorImage];
    
    // update TabBar when TabBarItem width did update
    // If your app need support UIDeviceOrientationLandscapeLeft or UIDeviceOrientationLandscapeRight，
    // remove the comment '//'
    // 如果你的App需要支持横竖屏，请使用该方法移除注释 '//'
    //[self updateTabBarCustomizationWhenTabBarItemWidthDidUpdate];
    
    //UITabBar * tabBarAppearance = tabBarController.tabBar;
    // set the bar shadow image
    // This shadow image attribute is ignored if the tab bar does not also have a custom background image.So at least set somthing.
    //[tabBarAppearance setShadowImage:[UIImage new]];
    
    // set the bar background image
    //设置背景图片
    //[tabBarAppearance setBackgroundImage:[UIImage imageWithColor:kColor_MDHHex(@"180043")]];
}

- (void)updateTabBarCustomizationWhenTabBarItemWidthDidUpdate {
    void (^deviceOrientationDidChangeBlock)(NSNotification *) = ^(NSNotification *notification) {
        UIDeviceOrientation orientation = [[UIDevice currentDevice] orientation];
        if ((orientation == UIDeviceOrientationLandscapeLeft) || (orientation == UIDeviceOrientationLandscapeRight)) {
            NSLog(@"Landscape Left or Right !");
        } else if (orientation == UIDeviceOrientationPortrait) {
            NSLog(@"Landscape portrait!");
        }
        [self customizeTabBarSelectionIndicatorImage];
    };
    [[NSNotificationCenter defaultCenter] addObserverForName:CYLTabBarItemWidthDidChangeNotification
                                                      object:nil
                                                       queue:[NSOperationQueue mainQueue]
                                                  usingBlock:deviceOrientationDidChangeBlock];
}

- (void)customizeTabBarSelectionIndicatorImage {
    ///Get initialized TabBar Height if exists, otherwise get Default TabBar Height.
    UITabBarController *tabBarController = [self cyl_tabBarController] ?: [[UITabBarController alloc] init];
    CGFloat tabBarHeight = tabBarController.tabBar.frame.size.height;
    CGSize selectionIndicatorImageSize = CGSizeMake(CYLTabBarItemWidth, tabBarHeight);
    //Get initialized TabBar if exists.
    UITabBar *tabBar = [self cyl_tabBarController].tabBar ?: [UITabBar appearance];
    [tabBar setSelectionIndicatorImage:[[UIImage imageWithColor:[UIColor redColor]] imageByResizeToSize:selectionIndicatorImageSize]];
}

/**
 * 如果window的根视图是UITabBarController，则会先调用这个Category，然后调用UIViewController+ZFPlayerRotation
 * 只需要在支持除竖屏以外方向的页面重新下边三个方法
 */

/*
// 是否支持自动转屏
- (BOOL)shouldAutorotate {
    UIViewController *vc = self.tabBarController.viewControllers[self.selectedIndex];
    if ([vc isKindOfClass:[UINavigationController class]]) {
        UINavigationController *nav = (UINavigationController *)vc;
        return [nav.topViewController shouldAutorotate];
    } else {
        return [vc shouldAutorotate];
    }
}

// 支持哪些屏幕方向
- (UIInterfaceOrientationMask)supportedInterfaceOrientations {
    if (self.selectedIndex >= self.viewControllers.count) {
        return [super supportedInterfaceOrientations];
    }
    UIViewController *vc = self.viewControllers[self.selectedIndex];
    if ([vc isKindOfClass:[UINavigationController class]]) {
        UINavigationController *nav = (UINavigationController *)vc;
        return [nav.topViewController supportedInterfaceOrientations];
    } else {
        return [vc supportedInterfaceOrientations];
    }
}
// 默认的屏幕方向（当前ViewController必须是通过模态出来的UIViewController（模态带导航的无效）方式展现出来的，才会调用这个方法）
- (UIInterfaceOrientation)preferredInterfaceOrientationForPresentation {
    UIViewController *vc = self.viewControllers[self.selectedIndex];
    if ([vc isKindOfClass:[UINavigationController class]]) {
        UINavigationController *nav = (UINavigationController *)vc;
        return [nav.topViewController preferredInterfaceOrientationForPresentation];
    } else {
        return [vc preferredInterfaceOrientationForPresentation];
    }
}
*/


@end
